/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlets;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.FlushModeType;
import javax.persistence.Persistence;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;

/**
 *
 * @author 
 */
public class BaseServlet extends HttpServlet {

    @Resource(name = "jndibbdd")
    public DataSource jdbcUAO;
    EntityManagerFactory emf;
    EntityManager em;

    @Override
    public void init() throws ServletException {
        super.init();
        //p = new PruebaPersistencia(jdbcUAO);
    }

    public boolean checkSession(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession(true);
        if (session.isNew() ||( session.getAttribute("alumno") == null && session.getAttribute("empleado")==null)) {
            System.out.println("gkgufgufufuf");
            session.invalidate();
            return false;
        }
        return true;
    }

    public void redirect(String url, HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + url));
    }

    public String safeURL(String url, HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        return response.encodeURL(request.getContextPath() + url);
    }

    public void include(String url, HttpServletRequest request, HttpServletResponse response) {
        try {
            RequestDispatcher rd = getServletContext().getRequestDispatcher(url);
            rd.include(request, response);
        } catch (ServletException ex) {
            Logger.getLogger(BaseServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(BaseServlet.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public void preparaBD() {
        emf = Persistence.createEntityManagerFactory("UAOProjectPU");
        em = emf.createEntityManager();
        em.setFlushMode(FlushModeType.AUTO);
        em.getTransaction().begin();
    }

    public void commitBD() {
        em.getTransaction().commit();
        em.close();
    }


    /** Returns a short description of the servlet.*/
    @Override
    public String getServletInfo() {
        return "Short description";
    }
}
